/**
 * Created by liubin on 2015/09/17.
 */
'use strict';

import Request from 'superagent-bluebird-promise';
//import Cookies from 'js-cookie';
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';
export const AUTH = 'AUTH';

export const Authorization = {
    ANONYMOUS: 'ANONYMOUS',
    USER: 'USER',
    ADMIN: 'ADMIN'
};

function getAuth(json) {
    return {
        type: AUTH,
        status: json.status
    };
}

export function auth() {
    // 异步处理
    return dispatch => {
        return Request.get('/api/auth/identity')
            .then(resp => {
                    dispatch(getAuth(resp.body));
                });
    };

}

function loginResult(json) {
    return {
        type: LOGIN,
        status: json.status
    };
}

function logoutResult(json) {
    return {
        type: LOGOUT,
        status: json.status
    };
}

export function login(data) {
    return {
        type: LOGIN,
        payload: {
            promise: Request.post('/api/auth/login').send(data).promise(),
            resolve: (resp, dispatch) => {
                dispatch(loginResult(resp.body));
            }
        //    reject: (error, dispatch) => {
        //        dispatch(loginResult(error.body));
        //    }
        }
    };
    //return (dispatch, getState) => {
    //    //return Request.post('/api/auth/login')
    //    //.send(data)
    //    ////.set('X-CSRFToken', Cookies.get('csrftoken'))
    //    //.then(resp => {
    //    //        dispatch(loginResult(resp.body));
    //    //    }, error => {
    //    //        dispatch(loginResult(error.body));
    //    //    })
    //    //.catch();
    //    //const promise = ;
    //    return {
    //        type: LOGIN,
    //        payload: {
    //            promise: Request.post('/api/auth/login').send(data).promise(),
    //            resolve: resp => {
    //                dispatch(loginResult(resp.body));
    //            },
    //            reject: error => {
    //                dispatch(loginResult(error.body));
    //            }
    //        }
    //    };
    //};
}
/**
 * 登出
 * @returns {{type: string, payload: {promise: *, resolve: Function}}}
 */
export function logout() {
    const promise = Request.get('/api/auth/logout').promise();
    return {
        type: LOGOUT,
        payload: {
            promise,
            resolve: (resp, dispatch) => {
                dispatch(logoutResult(resp.body));
            }
        //    reject: (error, dispatch) => {
        //        dispatch(loginResult(error.body));
        //    }
        }
    };
}